<?php

namespace app\admin\controller;

use app\common\model\User as UserModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Db;

/**
 * 用户管理
 * Class AdminUser
 * @package app\admin\controller
 */
class User extends AdminBase
{
    protected $model;
    protected $group_list;

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new UserModel();

        $this->assign('group_list', $this->group_list);
    }

    /**
     * 用户管理
     * @param string $keyword
     * @param int $page
     * @return mixed
     */
    public function index($keyword = '', $page = 1)
    {
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $perpage = isset($_REQUEST['perpage']) ? $_REQUEST['perpage'] : 10;

        $keyword = isset($_REQUEST['keyword']) ? trim($_REQUEST['keyword']) : '';

        $map = [];
        if ($keyword) {
            $map['username|mobile|email'] = ['like', "%{$keyword}%"];
        }


        $user_list = $this->model->where($map)->order('id DESC')->paginate(10);

        $this->assign(array('keyword' => $keyword, 'perpage' => $perpage));

        return $this->fetch('index', ['user_list' => $user_list, 'keyword' => $keyword]);
    }

    public function toggle($id, $status, $name)
    {
        if ($this->request->isGet()) {

            if ($this->model->where('id', $id)->update([$name => $status]) !== false) {
                return json(array('code' => 200, 'msg' => '更新成功'));
            } else {
                return json(array('code' => 0, 'msg' => '更新失败'));
            }
        }

    }

    /**
     * 添加用户
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存用户
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate_result = $this->validate($data, 'User');

            if ($validate_result !== true) {
                return json(array('code' => 0, 'msg' => $validate_result));
            } else {

                $data['uuid'] = guid();
                $data['salt'] = generate_password(18);
                $data['password'] = md5($data['password'] . $data['salt']);
                if ($this->model->allowField(true)->save($data)) {
                    return json(array('code' => 200, 'msg' => '添加成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '添加失败'));
                }
            }
        }
    }

    /**
     * 批量创建用户
     */
    public function batchAddUser()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();

            //从官网获取随机用户名
            $res = UserModel::getRandNames($params['num']);
            if (!$res['data']) {
                return json(array('code' => 0, 'msg' => '未能用官方服务器获取到数据，请手动创建吧'));
            }
            $names = $res['data'];
            $realNum = count($names);
            $data = [];
            for ($i = 0; $i < $realNum; $i++) {
                //先判断是不是存在
                $name = trim($names[$i]);
                $find = UserModel::get(['username', $name]);
                if ($find) continue;
                $_data['uuid'] = guid();
                $_data['salt'] = generate_password(18);
                $_data['avatar'] = '/public/images/userhead/' . $i . '.jpg';
                $_data['username'] = 'u_'.generate_password(6);
                $_data['nickname'] = $name;
                $_data['system_used'] = 1;
                $_data['no_audit'] = 1;
                $_data['password'] = md5($params['password'] . $_data['salt']);
                $data[] = $_data;
            }
            if ($this->model->insertAll($data)) {
                return json(array('code' => 200, 'msg' => '成功创建'.count($data).'个系统专用账号,密码均为'.$params['password']));
            } else {
                return json(array('code' => 0, 'msg' => '添加失败'));
            }
        }

    }

    /**
     * 编辑用户
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $user = $this->model->find($id);

        return $this->fetch('edit', ['user' => $user]);
    }

    /**
     * 更新用户
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $validate_result = $this->validate($data, 'User');

            if ($validate_result !== true) {
                return json(array('code' => 0, 'msg' => $validate_result));
            } else {
                $user = $this->model->find($id);
                if ($data['email']) {
                    $map['email'] = $data['email'];
                    $map['id'] = ['neq', $id];
                    $hasuserhead = Db::name('user')->where($map)->count();
                    if ($hasuserhead > 0) {
                        return json(array('code' => 0, 'msg' => '邮箱重复'));
                    }
                }

                if (!empty($data['password']) && !empty($data['confirm_password'])) {
                    $data['password'] = md5($data['password'] . $user['salt']);
                }
                if ($this->model->allowField(true)->save($data, ['id' => $data['id']])) {
                    return json(array('code' => 200, 'msg' => '更新成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '更新失败'));
                }
            }
        }
    }

    /**
     * 删除用户
     * @param $id
     */
    public function delete($id)
    {
        if($id==1){
            return json(array('code' => 0, 'msg' => '系统用户禁止删除！'));
        }
        if ($this->model->destroy($id)) {
            return json(array('code' => 200, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }
}